package com.qk.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.qk.util.CurrentUserContextHolders;
import com.qk.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/11 15:38
 * @Description: 登录拦截器
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class LoginInterceptor implements HandlerInterceptor {

    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (StrUtil.isEmpty(token)) {
            log.info("---请求没有token，拒绝访问---");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Map<String, Object> claims = JWTUtils.parseToken(token);
            log.info("----用户id：{}，用户username：{}----", claims.get(JWTUtils.KEY_ID), claims.get(JWTUtils.KEY_USERNAME));
            CurrentUserContextHolders.setId((Integer) claims.get(JWTUtils.KEY_ID));
            CurrentUserContextHolders.setName((String) claims.get(JWTUtils.KEY_USERNAME));
        } catch (Exception e) {
            log.info("---解析token失败，拒绝访问---");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        log.info("---token正确，请求通过---");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.removeId();
        CurrentUserContextHolders.removeName();
    }
}
